import requests
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def login():
    """Login to the API and return sessionId and accessToken"""
    url = "https://172.16.25.114:10002/uas/v1/api/user/login"
    
    payload = {
        "captcha": "ut0z",
        "agentType": 1,
        "username": "sysadmin",
        "password": "Allcam@2025",
        "clientNonce": "wcs0520240808104845898chid",
        "cuType": "1"
    }
    
    headers = {
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.post(url, headers=headers, json=payload, verify=False)
        response.raise_for_status()
        
        data = response.json()
        
        # Extract sessionId and accessToken from response
        session_id = data.get('sessionId')
        access_token = data.get('accessToken')
        
        print(f"Login successful. Session ID: {session_id}, Access Token: {access_token}")
        print(f"Full login response: {json.dumps(data, indent=2)}")
        
        return session_id, access_token
    except requests.exceptions.RequestException as e:
        print(f"Login failed: {e}")
        if hasattr(e, 'response') and e.response is not None:
            try:
                error_response = e.response.json()
                print(f"Error response: {json.dumps(error_response, indent=2)}")
            except:
                print(f"Error response text: {e.response.text}")
        return None, None


def favorite_collect(session_id, access_token, favorite_id, oprType):
    """Make a request to the favorite collect endpoint"""
    url = "https://172.16.25.114:10002/uas/v1/api/favorite/collect"
    
    payload = {
        "cameraId": "00000025071405000301000000011586",
        "favoriteId": favorite_id,
        "operType": oprType,
        "clientNonce": session_id,
        "cuType": "1"
    }
    
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }
    
    try:
        response = requests.post(url, headers=headers, json=payload, verify=False)
        response.raise_for_status()
        
        response_data = response.json()
        print(f"Favorite collect request successful for favoriteId: {favorite_id}")
        print(f"Response: {json.dumps(response_data, indent=2)}")
        return {"favoriteId": favorite_id, "status": "success", "response": response_data}
    except requests.exceptions.RequestException as e:
        print(f"Favorite collect request failed for favoriteId: {favorite_id}, Error: {e}")
        # Try to get response details if available
        if hasattr(e, 'response') and e.response is not None:
            try:
                error_response = e.response.json()
                print(f"Error response: {json.dumps(error_response, indent=2)}")
            except:
                print(f"Error response text: {e.response.text}")
        return {"favoriteId": favorite_id, "status": "failed", "error": str(e)}


def run_concurrent_requests(session_id, access_token, favorite_ids, oprType):
    """Run concurrent requests to the favorite collect endpoint"""
    results = []
    
    with ThreadPoolExecutor(max_workers=min(len(favorite_ids), 10)) as executor:
        # Submit all tasks
        future_to_favorite = {
            executor.submit(favorite_collect, session_id, access_token, fav_id, oprType): fav_id
            for fav_id in favorite_ids
        }
        
        # Collect results as they complete
        for future in as_completed(future_to_favorite):
            result = future.result()
            results.append(result)
    
    return results


def main():
    """Main function to execute the test"""
    print("Starting API test...")
    
    # Step 1: Login to get sessionId and accessToken
    session_id, access_token = login()
    
    if not session_id or not access_token:
        print("Login failed. Cannot proceed with tests.")
        return
    
    # List of favoriteIds for concurrent requests
    favorite_ids = [
        "acs202412041016032529dpribZwdpfO",
        "acs20241125143028130jNLtGDwU8pmY"
    ]
    
    print(f"Starting concurrent requests with {len(favorite_ids)} favorite IDs...")
    
    # Step 2: Concurrent requests to favorite collect endpoint
    start_time = time.time()
    results = run_concurrent_requests(session_id, access_token, favorite_ids, "1")
    end_time = time.time()
    
    print(f"\nCompleted {len(results)} requests in {end_time - start_time:.2f} seconds")
    
    # Print results summary
    success_count = sum(1 for result in results if result['status'] == 'success')
    failed_count = len(results) - success_count

    print(f"\nResults Summary:")
    print(f"Successful requests: {success_count}")
    print(f"Failed requests: {failed_count}")

    run_concurrent_requests(session_id, access_token, favorite_ids, "0")

    print("\nDetailed Results:")
    for result in results:
        if result['status'] == 'success':
            print(f"\n✓ Success for favoriteId: {result['favoriteId']}")
            print(f"Response: {json.dumps(result['response'], indent=2)}")
        else:
            print(f"\n✗ Failed for favoriteId: {result['favoriteId']}")
            print(f"Error: {result['error']}")

if __name__ == "__main__":
    main()